import { List, SearchBar } from 'antd-mobile'
import React, { useState } from 'react'

import { API, getCity } from '../../../utils'

import styles from './index.module.css'

// 定时器id
let timerId = null

export default function RentSearch({ history }) {
  // 当前城市id
  const cityId = getCity().value

  const [searchTxt, setSearchTxt] = useState('')
  const [tipsList, setTipsList] = useState([])

  const handleSearchTxt = value => {
    setSearchTxt(value)

    if (!value) setTipsList([])

    // 清除上一次定时器
    clearTimeout(timerId)

    timerId = setTimeout(async () => {
      // 获取小区数据
      const { data: res } = await API.get('/area/community', {
        params: {
          name: value,
          id: cityId
        }
      })
      setTipsList(res.body)
    }, 500)
  }

  const onTipsClick = item => {
    console.log(item)
    history.replace('/rent/add', {
      id: item.community,
      name: item.communityName
    })
  }

  return (
    <div className={styles.root}>
      {/* 搜索框 */}
      <div className={styles.search}>
        <SearchBar
          value={searchTxt}
          showCancelButton={() => true}
          placeholder="请输入小区或地址"
          onChange={value => handleSearchTxt(value)}
          onCancel={() => history.push('/rent/add')}
          clearOnCancel={false}
          style={{ '--background': '#fff', width: '100%', '--height': '30px' }}
        />
      </div>

      <List>
        {tipsList.map((item, i) => (
          <List.Item key={i} onClick={() => onTipsClick(item)}>
            {item.communityName}
          </List.Item>
        ))}
      </List>
    </div>
  )
}
